import { computed, defineComponent, h, onMounted, ref, watch } from "vue";
import { cloneDeep } from "lodash-es";

export const matrixScaleProps = {
  value: {
    type: Object,
    default: () => {}
  },
  table: {
    type: Object,
    default: () => {}
  },
  icon: {
    type: String,
    default: "tduck-star"
  },
  iconColor: {
    type: String,
    default: "#f7ba2a"
  }
};

export function useMatrixScale(props: any, emit: any) {
  const rateIcons: any = {
    "tduck-star": defineComponent({
      setup() {
        return () => h("i", { class: `iconfont tduck-star` });
      }
    }),
    "tduck-taiyang": defineComponent({
      setup() {
        return () => h("i", { class: `iconfont tduck-taiyang` });
      }
    }),
    "tduck-biaoqing-weixiao": defineComponent({
      setup() {
        return () => h("i", { class: `iconfont tduck-biaoqing-weixiao` });
      }
    }),
    "tduck-dianzan": defineComponent({
      setup() {
        return () => h("i", { class: `iconfont tduck-dianzan` });
      }
    }),
    "tduck-aixin": defineComponent({
      setup() {
        return () => h("i", { class: `iconfont tduck-aixin` });
      }
    }),
    "tduck-moonyueliang": defineComponent({
      setup() {
        return () => h("i", { class: `iconfont tduck-moonyueliang` });
      }
    })
  };

  const dataValue = ref({});

  // 初始化矩阵value为二维数组
  const initValue = (value: any) => {
    let cloneValue = cloneDeep(value);
    if (value) {
      dataValue.value = cloneValue;
    } else {
      dataValue.value = {};
    }
  };

  const getTableRows = computed(() => {
    return props.table.rows;
  });

  onMounted(() => {
    initValue(props.value);
  });

  const handleChange = (val: any) => {
    emit("update:value", dataValue.value);
    emit("change", dataValue.value);
  };

  const getCurrentIcon = computed(() => {
    return rateIcons[props.icon];
  });

  watch(
    () => props.table,
    () => {
      initValue(props.value);
    },
    { deep: true }
  );

  watch(
    () => props.value,
    val => {
      initValue(val);
    },
    { deep: true }
  );

  return {
    rateIcons,
    initValue,
    getTableRows,
    handleChange,
    getCurrentIcon,
    dataValue
  };
}
